#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
import json


class YunnanYgycPolicy(BaseTaxPolicySpider):
    name = 'yunnan_ynczt2_policy'
    
    province = '云南省'
    # city = '昆明市'
    # county = '安宁市'
    park = ''
    # source = '安宁市人民政府'
    city = ''
    county = ''
    url = 'https://czt.yn.gov.cn/zfxxgk.html?id=1458332232845484033&pid=1'

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                "DOWNLOADER_MIDDLEWARES": {
                    # "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        url = "https://czt.yn.gov.cn/jeecg-boot/index/tbArticle/list?"
        params = {
            "pageNo": "1",
            "pageSize": "50",
            "catgoryid": "1458332232845484033",
        }
        meta = {"params": params, "url": url}
        yield scrapy.Request(url + urllib.parse.urlencode(params), callback=self.parse_list, meta=meta)

    def parse_list(self, response, **kwargs):
        meta = response.meta
        data = response.json()['result']
        prev_item = response.meta.get('item')
        for elem in data['records']:
            item = Item()
            if elem['outurl']:
                item['source_url'] = elem['outurl']
            else:
                item['source_url'] = f"https://czt.yn.gov.cn/news_des.html?id=1745883671286711426&cid={elem['id']}"
            item['publish_date'] = elem['createTime'].split(' ')[0]
            item['title'] = elem['title']
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = data['pages']
            for page_num in range(2, int(total_page) + 1):
                params = meta['params']
                params['pageNo'] = page_num
                url = meta['url']
                yield response.follow(url + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # data = json.loads(self.aes_ecb_decrypt(response.text.encode('utf-8')))
        # region = data['data']['region']
        item['content'] = response.xpath(""".""").get()
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_ynczt2_policy".split())
